package com.usian.pay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.domain.ExtUserInfo;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.usian.jyzx.model.entity.order.OrderInfo;
import com.usian.jyzx.model.entity.pay.PaymentInfo;
import com.usian.pay.config.MessageQueueHelper;
import com.usian.pay.fegin.OrderFegin;
import com.usian.pay.mapper.PaymentInfoMapper;
import com.usian.pay.service.AliPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @TODO:
 * @Author:baimu
 * @Date:2024 07 17 15 02
 **/
@Service
@Slf4j
public class AliPayServiceImpl implements AliPayService {

    @Value("${alipay.appId}")
    String appId;

    @Value("${alipay.privateKey}")
    String privateKey;
    @Value("${alipay.alipayPublicKey}")
    String alipayPublicKey;
    @Value("${alipay.notifyUrl}")
    String notifyUrl;
    @Value("${alipay.returnUrl}")
    String returnUrl;
    @Value("${alipay.serverUrl}")
    String serverUrl;
    @Value("${alipay.format}")
    String format;
    @Value("${alipay.charset}")
    String charset;
    @Value("${alipay.signType}")
    String signType;
    @Value("${alipay.subject}")
    String subject;
    @Value("${alipay.productCode}")
    String productCode;

    @Autowired

    OrderFegin orderFegin;
@Autowired
    PaymentInfoMapper paymentInfoMapper;

    @Autowired
    MessageQueueHelper messageQueueHelper;

    @Override
    public String pay( String orderId) throws AlipayApiException {
        OrderInfo orderInfo = orderFegin.findPayOrderByorderId(orderId);
        if(null==orderInfo){
            return "";
        }


        //应用私钥:
        //支付宝公钥:
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl(serverUrl);
        //支付宝分配给开发者的应用ID
        alipayConfig.setAppId(appId);

        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat(format);
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset(charset);
        alipayConfig.setSignType(signType);

        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        request.setNotifyUrl(notifyUrl);
        request.setReturnUrl(returnUrl);
        //商户订单号
        model.setOutTradeNo(orderId);
        //订单总金额。 单位为元
        model.setTotalAmount(orderInfo.getTotalAmount()+"");
        //订单标题。
        model.setSubject(subject);
        //产品码。 商家和支付宝签约的产品码。 枚举值（点击查看签约情况）： QUICK_WAP_WAY：手机网站支付产品。 默认值为 QUICK_WAP_WAY
        model.setProductCode(productCode);
        model.setBody(String.valueOf(orderInfo.getUserId()));
        ExtUserInfo extUserInfo = new ExtUserInfo();
        extUserInfo.setCertNo(String.valueOf(orderInfo.getUserId()));
        model.setExtUserInfo(extUserInfo);
        // model.setSellerId("2088102147948060");
        request.setBizModel(model);
        AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "POST");
        // 如果需要返回GET请求，请使用
        // AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "GET");
        String pageRedirectionData = response.getBody();
        System.out.println(pageRedirectionData);
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }

        return pageRedirectionData;
    }

    @Override
    public String notifyOrder(Map requestParams) {
        //获取支付宝POST过来反馈信息，将异步通知中收到的待验证所有参数都存放到map中
        Map< String , String > params = new HashMap< String , String >();
        log.info("支付宝开始通知的参数：{}",requestParams);
        for(Iterator iter = requestParams.keySet().iterator(); iter.hasNext();){
            String name = (String)iter.next();
            String[] values = (String [])requestParams.get(name);
            String valueStr = "";
            for(int i = 0;i < values.length;i ++ ){
                valueStr =  (i==values.length-1)?valueStr + values [i]:valueStr + values[i] + ",";
            }
            params.put (name,valueStr);
        }

        log.info("处理支付宝传过来的的参数：{}",params);

        //调用SDK验证签名
        //公钥验签示例代码
        try {
            boolean  signVerified = AlipaySignature.rsaCheckV1(params, alipayPublicKey, charset,signType) ;
            log.info("开始验签：{}",signVerified);
            if(signVerified){
                log.info("开始处理订单");
                //trade_status

                String tradeStatus = params.get("trade_status");
                if(tradeStatus.equals("TRADE_SUCCESS")||tradeStatus.equals("TRADE_FINISHED")){
                    PaymentInfo paymentInfo = new PaymentInfo();
                    paymentInfo.setOrderNo(params.get("out_trade_no"));
                    paymentInfo.setAmount(new BigDecimal(params.get("total_amount")));
                    paymentInfo.setCallbackContent(JSON.toJSONString(params));
                    paymentInfo.setPaymentStatus(1);
                    paymentInfo.setContent(params.get("subject"));
                    paymentInfo.setCallbackTime(new Date());
                    paymentInfo.setPayType(2);
                    paymentInfo.setCreateTime(new Date());
                    paymentInfo.setUserId(Long.valueOf(params.get("body")));
                    paymentInfoMapper.savePayMentInfo(paymentInfo);


                    log.info("买家付款成功,使用消息队列通知");
                    messageQueueHelper.sendMessage("pay-ex","pay-queue","paymentinfo",paymentInfo);


                    return "success";
                }else {
                    PaymentInfo paymentInfo = new PaymentInfo();
                    paymentInfo.setOrderNo(params.get("out_trade_no"));
                    paymentInfo.setAmount(new BigDecimal(params.get("total_amount")));
                    paymentInfo.setCallbackContent(JSON.toJSONString(params));
                    paymentInfo.setPaymentStatus(0);
                    paymentInfo.setContent(params.get("subject"));
                    paymentInfo.setCallbackTime(new Date());
                    paymentInfo.setPayType(2);
                    paymentInfo.setCreateTime(new Date());
                    paymentInfo.setUserId(Long.valueOf(params.get("body")));
                    paymentInfoMapper.savePayMentInfo(paymentInfo);

                }

            }
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
